package controllers

import (
	"github.com/astaxie/beego"
	"helloCms/models"
	"github.com/astaxie/beego/orm"
)

type HomeController struct {
	beego.Controller
}

func (c *HomeController)Index()  {
	c.TplName="Home/Index.html"
}



func (c *HomeController)GetMenus()  {
	userId:=c.GetSession("userId").(int)

	userInfo:=models.Userinfo{Id:userId}
	o:=orm.NewOrm()

	actions:=make([]models.Actioninfo,0)
	userActions:=make([]models.Useraction,0)
	o.LoadRelated(&userInfo,"Roles")

	//userName:=c.GetSession("userName").(string)
	//if userName=="111"{
	//	o.QueryTable("actioninfo").All(&actions)
	//	goto i
	//}


	for _,role:=range userInfo.Roles{
		o.LoadRelated(role,"Actions")//通过用户-角色-权限 查询用户具有的权限

		userActions1:=make([]models.Useraction,0)
		o.QueryTable("useraction").Filter("users_id",userId).All(&userActions1)//查询用户-权限 中该用户的所有设置
		actionArr:=make([]*models.Actioninfo,0)
		for _,v:=range userActions1 {
			flag:=true
			for _,v1:=range role.Actions{
				if v.Actions.Id==v1.Id{
					flag=false
					continue
				}
			}
			if flag {
				actionArr=append(actionArr,v.Actions)
			}
		}
		role.Actions=append(role.Actions,actionArr...)//将用户-角色-权限 得到的权限和用户-权限 得到的不重复权限合并

		for _,action:=range role.Actions{
			if action.ActionTypeEnum==1 { //判断是否为菜单权限
				o.QueryTable("useraction").Filter("actions_id",action.Id).All(&userActions)
				if len(userActions)>0{ //查到了用户-权限 中有该用户的权限设置
					for _,userAction:=range userActions{
						if userAction.IsPass==0{//判断权限是否被禁用
							continue
						}else { //userAction.IsPass==1
							actions=append(actions,*action)
						}
					}
				}else {//没有查到用户-权限 中有该用户的权限设置
					actions=append(actions,*action)
				}
			}
		}
	}
	//i:
	c.Data["json"]=map[string]interface{}{"menus":actions}
	c.ServeJSON()
}